#include "text.h"

#include <stdexcept>

using namespace std;

namespace GL
{

Text::Text()
: m_pFont(NULL)
, m_PosX(0.f)
, m_PosY(0.f)
{
    string fontPath = DATADIR"/glover/fonts/arial.ttf";
    m_pFont = new FTGLPolygonFont(fontPath.c_str());

    if (m_pFont->Error())
    {
        delete m_pFont;
        throw(logic_error("Failed to open font: " + fontPath));
    }

    m_pFont->FaceSize(24);
    setColor(255, 255, 255);
}

Text::~Text()
{
    delete m_pFont;
}

void Text::setSize(const int size)
{
    if (m_pFont)
    {
        m_pFont->FaceSize(size);
    }
}

void Text::setText(const string& text)
{
    m_Text = text;
}

void Text::setPosition(const float x, const float y)
{
    m_PosX = x;
    m_PosY = y;
}

void Text::setColor(const int r, const int g, const int b, const int a)
{
    m_Color[0] = r / 255.f;
    m_Color[1] = g / 255.f;
    m_Color[2] = b / 255.f;
    m_Color[3] = a / 255.f;
}

void Text::render()
{
    if (!m_pFont)
    {
        return;
    }

    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
    glLoadIdentity();

    glPushAttrib(GL_CURRENT_BIT | GL_MULTISAMPLE_BIT_ARB | GL_LIGHTING_BIT);
    glEnable(GL_MULTISAMPLE_ARB);
    glDisable(GL_LIGHTING);
    glDisable(GL_TEXTURE_2D);

    glColor4fv(m_Color);
    glTranslatef(m_PosX, m_PosY, 0);

    m_pFont->Render(m_Text.c_str());
    glPopAttrib();

    glPopMatrix();
}

Text::BBox Text::getBBox()
{
    BBox bbox;

    if (m_pFont)
    {
        m_pFont->BBox(m_Text.c_str(),
                      bbox.minX, bbox.minY, bbox.minZ,
                      bbox.maxX, bbox.maxY, bbox.maxZ);
    }
    return bbox;
}

}
